function fsb_file_write(FileName,idat,sandbox,scaninfo)

% FSB :  write files in fMRI sandbox format to disk
%
% EXAMPLE:
% fsb_file_write(idat,fileName,header_template,typ_e,gopt)
%
% INPUT:
% fileName: Name of file to write
% idat :     4-D image dataset or string
% sandbox: sandbox experiment struct
% scaninfo: scaninfo scan information
%
% OUTPUT:
% files in proprietary FSB format
%
% CALLED BY:
% FSB.m
% fsb_export.m
% fsb_prepare_SPM.m
% fsb_realign_SPM.m
% fsb_SPM5.m
% fsb_SPM.m
%
% NOTES:
% uses avw_img_write and spm_hwrite to write files.
% Using avw_img_write alone will result in faulty headers
%
% Steffen Stoewer 2011 stoewer@tuebingen.mpg.de
%
% Copyright 2011 MPI for Biological Cybernetics
% Author: Steffen Stoewer
% License:GNU GPL, no express or implied warranties
%
% $Revision 1.0
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~

% Save image information, if available
if exist('idat','var');
    whos('idat');
    save (FileName,'idat');
    disp('...done')
end

% Save scan information, if available
if exist('scaninfo','var');
    whos('scaninfo');
    save (FileName,'scaninfo','-append');
    disp('Verifying...');
    temp = load(FileName,'scaninfo');
    if ~isfield(temp,'sandbox');
        disp('Saving scan information failed...')
    else
        disp('...done')
    end
end

% Convert experiment information to SPM friendly format

if isfield(sandbox,'hemodynamics') && ~isempty(sandbox.hemodynamics);
    sandbox.hemodynamics = double(sandbox.hemodynamics);
    try
        % Preparation for SPM analysis
        sandbox = fsb_conv_onsets_time(sandbox);
    catch
        errmsg = lasterror;
        fsb_error_handler(errmsg)
        disp('Preparation for SPM analysis not successful')

    end
end

if isfield(sandbox,'hemodynamics_deriv') && ~isempty(sandbox.hemodynamics_deriv);
    sandbox.hemodynamics_deriv = double(hemodynamics_deriv);
end

% Save experiment information, if available

if exist('sandbox','var');
    try
        whos('sandbox');
        try % for compatibility with older datasets
            for ii = 1:size(sandbox.sb)
                sandbox.sb{ii} = rmfield(sandbox.sb{ii},'sb');
            end
        end
        try % for compatibility with older datasets
            sandbox = rmfield(sandbox,'stats');
        end
        save (FileName,'sandbox','-append');
        disp('Verifying...');
        temp = load(FileName,'sandbox');
        if ~isfield(temp,'sandbox');
            disp('Saving experiment information failed...');
            save (FileName,'sandbox','-append');
            %                             save tmp.mat -struct sandbox;
            %                             disp('Created struct tmp.mat with variables');

        end
    catch
        disp('No experiment information available')
    end
else

    disp('...done')

end